<?php

namespace App\Models;

use App\Http\Controllers\Admin\CommonController;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;



/**
 * 书店书籍采购表
 * Class BookHomePurchaseModel
 * @package app\common\model
 */
class BookHomePurchase extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'book_home_purchase';

    //   protected $insert = ['create_time' , 'return_state'=>1,'settle_state'=>3];

    /*public function setExpireTimeAttr(){
        $day = BookHomePurchaseSetModel::where('type' , 12)->value('number');
        $day = empty($day) ? 30 : (int)$day;
        return date('Y-m-d H:i:s' , strtotime("+$day day"));
    }*/

    /**
     * 获取条形码
     * @param $book_id 书籍id
     * @param $order_id 订单id
     * @param $account_id 读者证号id
     */
    public function getBarcode($book_id, $order_id, $account_id)
    {
        $barcode = $this->where('book_id', $book_id)
            ->where('order_id', $order_id)
            ->where('account_id', $account_id)
            ->orderByDesc('id')
            ->value('barcode');
        return $barcode;
    }

    /**
     * 添加用户借阅数量及金额
     * @param account_id 账号id
     * @param book_infos  书籍信息  数组形式
     */
    public function  insertAccountBorrowMoneyNumber($account_id, $book_infos)
    {
        $account_info = UserLibraryInfo::find($account_id);
        if (empty($account_id)) throw new \Exception('读者信息获取失败');

        $price = array_column($book_infos, 'price');
        $now_price = array_sum($price);
        $now_num = count($price);

        //获取 年借阅本书
        if (!empty($account_info['s_time']) && $account_info['e_time'] > date('Y-m-d H:i:s')) {
            $account_info->recomed_num  = $account_info['recomed_num'] + $now_num; //年借阅本书
            $account_info->recomed_money  = $account_info['recomed_money'] + $now_price; //年借阅金额
        } else {
            $account_info->s_time = date('Y-m-d H:i:s');
            $account_info->e_time = date('Y-m-d H:i:s', strtotime("+1 year"));
            $account_info->recomed_num  = $now_num; //年借阅本书
            $account_info->recomed_money  = $now_price; //年借阅金额
        }
        //获取月借阅本书
        if (!empty($account_info['last_mmm']) && $account_info['last_mmm'] == date('Ym')) {
            $account_info->last_num  = $account_info['last_num'] + $now_num; //本月采购本书
            $account_info->last_money  = $account_info['last_money'] + $now_price; //本月采购金额
        } else {
            $account_info->last_mmm = date('Ym');
            $account_info->last_num  = $now_num; //本月采购本书
            $account_info->last_money = $now_price; //本月采购金额
        }

        $account_info->purch_num_shop = !empty($account_info['purch_num_shop']) ? $account_info['purch_num_shop'] + $now_num : $now_num;
        $account_info->purch_money_shop = !empty($account_info['purch_money_shop']) ? $account_info['purch_money_shop'] + $now_price : $now_price;

        $account_info->last_time = date("Y-m-d H:i:s");
        $account_info->change_time = date("Y-m-d H:i:s");

        $account_info->save();
    }



    /**
     * 获取逾期归还每天的滞纳金 和丢失赔付的比例
     * @param overdue_money  逾期金额
     * @param overdue_number  逾期天数
     * @param drop_money  丢失赔付金额
     * @param price  总价
     */
    public function penalSumParam($overdue_money, $overdue_number, $drop_money, $price)
    {
        $overdue_ratio = 0;
        $drop_ratio = 0;
        if (!empty($overdue_money) && !empty($overdue_number)) {
            $overdue_ratio = sprintf("%.2f", $overdue_money / $overdue_number);
        }
        if (!empty($drop_money)) {
            $drop_ratio = (sprintf("%.2f", $drop_money / $price) * 100) . '%';
        }
        return [$overdue_ratio, $drop_ratio];
    }

    /**
     * 获取读者当前借阅信息
     * @param  account_id 读者证号id
     */
    public function getNowBorrowList($account_id)
    {
        $res = $this->from($this->getTable() . ' as p')
            ->select("p.id','p.create_time','p.expire_time','p.return_state','p.return_time','p.overdue_money','p.drop_money','p.total_money','p.price','p.isbn','b.book_name','b.author','b.press','b.pre_time','b.book_selector','s.name as shop_name")
            ->join('shop_book as b', 'b.id', '=', 'p.book_id')
            ->join('shop as s', 's.id', '=', 'b.shop_id')
            ->where('p.account_id', $account_id)
            ->where('p.return_state', "<>", 2)
            ->get();

        //计算逾期天数，丢失赔付金额
        foreach ($res as $key => &$val) {
            list($val['overdue_day'], $val['overdue_money'], $val['drop_money'], $val['total_money'], $val['overdue_ratio'], $val['drop_ratio']) = $this->getVirtualOverdueDayMoney($val);
            $val['explain'] = '如果书籍既丢失又逾期，则总金额为两者中的最大值，如果最大值超过了书籍本身的金额，则总金额为书籍本身价格'; //总金额说明文字
        }

        return $res ? $res : null;
    }

    /**
     * 计算逾期天数和逾期金额和 虚拟丢失赔付金额
     *
     * @param $is_drop 是否丢失  1 正常  2 已丢失
     */
    public function getVirtualOverdueDayMoney($data, $is_drop = 2)
    {
        $time = date('Y-m-d H:i:s');
        $BookHomePurchaseSetModel = new BookHomePurchaseSet();

        //获取逾期违约金
        $overdue_ratio = $BookHomePurchaseSetModel->where('type', 2)->value('number');
        //获取丢失赔付比例
        $drop_ratio = $BookHomePurchaseSetModel->where('type', 13)->value('number');

        if ($data['return_state'] == 3) {
            //归还中按照已归还计算逾期天数
            if ($data['return_time'] < $time) {
                $overdue_day = time_diff($data['return_time'], $time, false)['day'];
            } else {
                $overdue_day = 0;
            }
            $overdue_money = $data['overdue_money'];
            $drop_money = $data['drop_money'];
            $total_money = $data['total_money'];
        } else {
            if ($data['expire_time'] < $time) {
                $overdue_day = time_diff($data['expire_time'], $time, false)['day'];
                $overdue_money = sprintf("%.2f", $overdue_day * $overdue_ratio);
                $overdue_money = $overdue_money <= $data['price'] ? $overdue_money : $data['price'];
            } else {
                $overdue_day = 0;
                $overdue_money = '0';
            }

            $drop_money =  $is_drop == 2 ? sprintf("%.2f", $data['price'] * $drop_ratio / 100) : '0'; //计算虚拟丢失赔付金额

            $total_money = $drop_money > $overdue_money ? $drop_money : $overdue_money;
            $total_money = $total_money <= $data['price'] ? $total_money : $data['price'];
        }
        return [$overdue_day, $overdue_money, $drop_money, $total_money, $overdue_ratio, $drop_ratio . '%'];
    }

    /**
     * 计算实际逾期天数和金额
     */
    public function getOverdueDayMoney($data)
    {
        $time = date('Y-m-d H:i:s');

        if ($data['return_state'] == 2 || $data['return_state'] == 3) {
            //归还中按照已归还计算逾期天数
            if ($data['return_time'] > $data['expire_time']) {
                $overdue_day = time_diff($data['return_time'], $data['expire_time'], false)['day'];
            } else {
                $overdue_day = 0;
            }
        } else {
            if ($data['expire_time'] < $time) {
                $overdue_day = time_diff($data['expire_time'], $time, false)['day'];
            } else {
                $overdue_day = 0;
            }
        }
        return $overdue_day;
    }

    /**
     * 判断书籍是否有未归还或已归还的记录
     * @param BookHomePurchase_ids 一维数组 逗号拼接都可以
     */
    public function checkIsExceed($barcode, $user_id, $account_id)
    {
        $return_state = self::whereIn('barcode', $barcode)
            ->where('account_id', $account_id)
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('account_id', $account_id);
                } else {
                    $query->where('user_id', $user_id);
                }
            })
            ->where('return_state', 3)
            // ->where('return_state = 3 or return_state = 2')
            ->first();
        if (!empty($return_state)) {
            throw new \Exception('您选择的书籍存在已归还或归还中的记录，请勿重复选择');
        }
        return true;
    }


    /**
     * 获取正在归还中的记录
     */
    public function getReturnIng($account_id)
    {
        return $this->where('return_state', 3)->where('account_id', $account_id)->pluck('barcode')->toArray();
    }


    /**
     * 借阅统计
     * @param $type  类型 1 新书  2 馆藏书
     */
    public function getBorrowData($type = null, $user_id = null, $start_time = null, $end_time = null)
    {
        return $this->where(function ($query) use ($type, $user_id, $start_time, $end_time) {
            if ($type) {
                $query->where('type', $type);
            }
            if ($user_id) {
                $query->where('user_id', $user_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->count();
    }
    /**
     * 借阅统计  按月统计
     * @param $type  类型 1 新书  2 馆藏书Month
     */
    public function getBorrowMonthData($type = null, $user_id = null, $start_time = null, $end_time = null)
    {
        return $this->select(DB::raw("count(id) count"), DB::raw("DATE_FORMAT(create_time,'%Y-%m') month"))
            ->where(function ($query) use ($type, $user_id, $start_time, $end_time) {
                if ($type) {
                    $query->where('type', $type);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->group('month')
            ->get()
            ->toArray();
    }
    /**
     * 书店新书采购清单
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 发货开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 发货结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param way		采购方式   1 为 线上荐购 ， 2 为线下荐购
     * @param book_selector  是否套数   不传  或转空  或 0，表示全部  1 是 2 否
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param settle_sponsor_manage_id  发起结算的管理员id   不传  或转空  或 0，表示全部
     * @param return_manage_id  图书馆归还管理员id   不传  或转空  或 0，表示全部
     * @param settle_affirm_manage_id  确认结算管理员id   不传  或转空  或 0，表示全部
     * @param is_return 是否归还   不传  或转空  或 0，表示全部  1 借阅中  2 已归还   3 归还中
     * @param is_overdue 是否逾期   不传  或转空  或 0，表示全部  1 未逾期  2 已逾期
     * @param select_way  查询方式  1 分页列表  2 人次  3 总价格 4总数量
     * @param node   是否借阅成功  0全部 1成功  2 失败
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function lists($params)
    {
        $field = $params['field'] ?? null;
        $keywords = $params['keywords'] ?? null;
        $keywords_type = $params['keywords_type'] ?? null;
        $shop_id = $params['shop_id'] ?? null;
        $start_time = $params['start_time'] ?? null;
        $end_time = $params['end_time'] ?? null;
        $settle_state = $params['settle_state'] ?? null;
        $way = $params['way'] ?? null;
        $book_selector = $params['book_selector'] ?? null;
        $pur_manage_id = $params['pur_manage_id'] ?? null;
        $settle_sponsor_manage_id = $params['settle_sponsor_manage_id'] ?? null;
        $settle_affirm_manage_id = $params['settle_affirm_manage_id'] ?? null;
        $return_manage_id = $params['return_manage_id'] ?? null;
        $shop_all_id = $params['shop_all_id'] ?? null;
        $is_overdue = $params['is_overdue'] ?? 0;
        $is_return = $params['is_return'] ?? 0;
        $node = $params['node'] ?? 0;
        $type = $params['type'] ?? '';
        $select_way = $params['select_way'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $page = $params['page'] ?? 10;
        if (empty($field)) {
            $field = [
                'r.id', 'r.order_id', 'r.barcode', 'r.return_state', 'r.expire_time', 'r.return_time', 'l.username', 'l.account', 'b.book_name', 'b.author',
                'b.isbn', 'b.press', 'b.pre_time', 'b.book_selector', 'r.price', 'r.create_time', 'r.settle_state', 'r.settle_sponsor_time', 'r.settle_sponsor_manage_id',
                'r.pur_manage_id', 'r.return_manage_id', 's.name as shop_name', 'settle_affirm_manage_id', 'settle_affirm_time'
            ];
        }
        //  DB::enableQueryLog();
        $res = $this->from($this->getTable() . ' as r')
            ->select($field)
            ->join('user_account_lib as l', 'l.id', '=', 'r.account_id')
            ->join('shop_book as b', 'b.id', '=', 'r.book_id')
            ->join('shop as s', 's.id', '=', 'b.shop_id')
            ->where(function ($query) use ($keywords_type, $keywords) {
                if ($keywords) {
                    if ($keywords_type) {
                        switch ($keywords_type) {
                            case 1:
                                $query->where('b.book_name', 'like', "%$keywords%");
                                break;
                            case 2:
                                $query->where('b.author', 'like', "%$keywords%");
                                break;
                            case 3:
                                $query->where('b.isbn', 'like', "%$keywords%");
                                break;
                            case 4:
                                $query->where('l.account', 'like', "%$keywords%");
                                break;
                            case 5:
                                $query->where('r.barcode', 'like', "%$keywords%");
                                break;
                        }
                    } else {
                        $query->where('b.book_name', 'like', "%$keywords%")
                            ->orWhere('b.author', 'like', "%$keywords%")
                            ->orWhere('b.isbn', 'like', "%$keywords%")
                            ->orWhere('l.account', 'like', "%$keywords%")
                            ->orWhere('r.barcode', 'like', "%$keywords%");
                    }
                }
            })
            ->where(function ($query) use ($shop_id, $settle_state, $settle_sponsor_manage_id, $settle_affirm_manage_id, $pur_manage_id, $return_manage_id, $start_time, $end_time, $book_selector, $shop_all_id, $is_return, $node, $way, $type) {

                if (!empty($shop_id)) {
                    $query->where("r.shop_id", $shop_id);
                }
                if (!empty($settle_state)) {
                    $query->where("r.settle_state", $settle_state);
                }
                if (!empty($pur_manage_id)) {
                    $query->where("r.pur_manage_id", $pur_manage_id);
                }
                if (!empty($settle_sponsor_manage_id)) {
                    $query->where("r.settle_sponsor_manage_id", $settle_sponsor_manage_id);
                }
                if (!empty($settle_affirm_manage_id)) {
                    $query->where("r.settle_affirm_manage_id", $settle_affirm_manage_id);
                }
                if (!empty($return_manage_id)) {
                    $query->where("r.return_manage_id", $return_manage_id);
                }
                if (!empty($book_selector)) {
                    $query->where("b.book_selector", $book_selector);
                }
                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('r.create_time', [$start_time, $end_time]);
                }
                if (!empty($way)) {
                    if ($way == 1) {
                        $query->whereNotNull('r.order_id');
                    } else {
                        $query->whereNull('r.order_id');
                    }
                }

                if (!empty($shop_all_id)) {
                    $query->whereIn("r.shop_id", $shop_all_id);
                }

                //是否归还
                if (!empty($is_return)) {
                    $query->where("r.return_state", $is_return);
                }
                if (!empty($node)) {
                    $query->where("r.node", $node);
                }
                //1新书，2馆藏书
                if (!empty($type)) {
                    $query->where("r.type", $type);
                }
            })->where(function ($query) use ($is_overdue, $is_return) {
                //是否逾期
                if (!empty($is_overdue)) {
                    //分为 归还成功 的逾期与未归还的逾期
                    if ($is_overdue == 1) {
                        if (empty($is_return)) {
                            $query->orWhere(function ($querys) {
                                $querys->where('r.return_state', 1)->where('r.expire_time', '>', date('Y-m-d H:i:s'));
                            });
                            $query->orWhere(function ($queryss) {
                                $queryss->orWhere('r.return_state', 2)->whereColumn('r.return_time', '<', 'r.expire_time');
                            });
                            $query->orWhere(function ($querysss) {
                                $querysss->orWhere('r.return_state', 3)->whereColumn('r.return_time', '<', 'r.expire_time');
                            });
                        } elseif ($is_return == 1) {
                            $query->where('r.expire_time', '>', date('Y-m-d H:i:s'));
                        } elseif ($is_return == 2) {
                            $query->whereColumn('r.return_time', '<', 'r.expire_time');
                        } elseif ($is_return == 3) {
                            $query->whereColumn('r.return_time', '<', 'r.expire_time');
                        }
                    } else {
                        if (empty($is_return)) {
                            $query->orWhere(function ($querys) {
                                $querys->where('r.return_state', 1)->where('r.expire_time', '<', date('Y-m-d H:i:s'));
                            });
                            $query->orWhere(function ($queryss) {
                                $queryss->orWhere('r.return_state', 2)->whereColumn('r.return_time', '>', 'r.expire_time');
                            });
                            $query->orWhere(function ($querysss) {
                                $querysss->orWhere('r.return_state', 3)->whereColumn('r.return_time', '>', 'r.expire_time');
                            });
                        } elseif ($is_return == 1) {
                            $query->where('r.expire_time', '<', date('Y-m-d H:i:s'));
                        } elseif ($is_return == 2) {
                            $query->whereColumn('r.return_time', '>', 'r.expire_time');
                        } elseif ($is_return == 3) {
                            $query->whereColumn('r.return_time', '>', 'r.expire_time');
                        }
                    }
                }
            })
            ->where('r.type', 1)
            ->orderByDesc('r.id');

        if ($select_way == 1) {
            $res = $res->paginate($limit)
                ->toArray();
        } elseif ($select_way == 2) {
            $res = $res->groupBy('r.account_id')->pluck('id'); //groupBy  和  count 不能连用
            $res = count($res);
        } elseif ($select_way == 3) {
            $res = $res->sum('r.price');
        } elseif ($select_way == 4) {
            $res = $res->count();
        }

        if ($select_way == 1) {
            $commonControllerObj = new CommonController();
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['pur_manage_name'] = !empty($val['pur_manage_id']) ? Manage::getManageNameByManageId($val['pur_manage_id']) : '';
                $res['data'][$key]['settle_sponsor_manage_name'] = !empty($val['settle_sponsor_manage_id']) ? Manage::getManageNameByManageId($val['settle_sponsor_manage_id']) : '';
                $res['data'][$key]['settle_affirm_manage_name'] = !empty($val['settle_affirm_manage_id']) ? Manage::getManageNameByManageId($val['settle_affirm_manage_id']) : '';
                $res['data'][$key]['return_manage_name'] = !empty($val['return_manage_id']) ? Manage::getManageNameByManageId($val['return_manage_id']) : '';

                //计算逾期时间
                $res['data'][$key]['overdue_day'] = $this->getOverdueDayMoney($val);

                $res['data'][$key][$commonControllerObj->list_index_key] = $commonControllerObj->addSerialNumberOne($key, $page, $limit);
                $res['data'][$key]['way'] = empty($val['order_id']) ? 2 : 1; //1 为 线上荐购 ， 2 为线下荐购
            }
            $res = $commonControllerObj->disPageData($res);
        }
        return $res;
    }


    /**
     * 馆藏书书籍采购清单
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 发货开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 发货结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param settle_sponsor_manage_id  发起结算的管理员id   不传  或转空  或 0，表示全部
     * @param return_manage_id  图书馆归还管理员id   不传  或转空  或 0，表示全部
     * @param settle_affirm_manage_id  确认结算管理员id   不传  或转空  或 0，表示全部
     * @param is_return 是否归还   不传  或转空  或 0，表示全部  1 借阅中  2 已归还   3 归还中
     * @param is_overdue 是否逾期   不传  或转空  或 0，表示全部  1 未逾期  2 已逾期
     * @param select_way  查询方式  1 分页列表  2 人次  3 总价格 4总数量
     * @param node   是否借阅成功  0全部 1成功  2 失败
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function libLists($params)
    {
        $field = $params['field'] ?? null;
        $keywords = $params['keywords'] ?? null;
        $keywords_type = $params['keywords_type'] ?? null;
        $start_time = $params['start_time'] ?? null;
        $end_time = $params['end_time'] ?? null;
        $settle_state = $params['settle_state'] ?? null;
        $pur_manage_id = $params['pur_manage_id'] ?? null;
        $settle_sponsor_manage_id = $params['settle_sponsor_manage_id'] ?? null;
        $settle_affirm_manage_id = $params['settle_affirm_manage_id'] ?? null;
        $return_manage_id = $params['return_manage_id'] ?? null;
        $is_overdue = $params['is_overdue'] ?? 0;
        $is_return = $params['is_return'] ?? 0;
        $node = $params['node'] ?? 0;
        $select_way = $params['select_way'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $page = $params['page'] ?? 10;
        if (empty($field)) {
            $field = [
                'r.id', 'r.order_id', 'r.barcode', 'l.account', 'l.username', 'b.book_name', 'b.author', 'b.isbn', 'b.press', 'b.pre_time', 'r.node',
                'r.is_dispose', 'r.price', 'r.barcode', 'r.create_time', 'r.expire_time', 'r.return_time', 'r.return_state', 'r.settle_state', 'r.is_pay',
                'r.settle_sponsor_time', 'r.settle_sponsor_manage_id', 'r.pur_manage_id', 'r.return_manage_id'
            ];
        }

        $res = $this->from($this->getTable() . ' as r')
            ->select($field)
            ->join('user_account_lib as l', 'l.id', '=', 'r.account_id')
            ->join('lib_book as b', 'b.id', '=', 'r.book_id')
            ->where(function ($query) use ($keywords_type, $keywords) {
                if ($keywords) {
                    if ($keywords_type) {
                        switch ($keywords_type) {
                            case 1:
                                $query->where('b.book_name', 'like', "%$keywords%");
                                break;
                            case 2:
                                $query->where('b.author', 'like', "%$keywords%");
                                break;
                            case 3:
                                $query->where('b.isbn', 'like', "%$keywords%");
                                break;
                            case 4:
                                $query->where('l.account', 'like', "%$keywords%");
                                break;
                            case 5:
                                $query->where('r.barcode', 'like', "%$keywords%");
                                break;
                        }
                    } else {
                        $query->where('b.book_name', 'like', "%$keywords%")
                            ->orWhere('b.author', 'like', "%$keywords%")
                            ->orWhere('b.isbn', 'like', "%$keywords%")
                            ->orWhere('l.account', 'like', "%$keywords%")
                            ->orWhere('r.barcode', 'like', "%$keywords%");
                    }
                }
            })
            ->where(function ($query) use ($settle_state, $settle_sponsor_manage_id, $settle_affirm_manage_id, $pur_manage_id, $return_manage_id, $start_time, $end_time, $is_return, $node) {
                if (!empty($settle_state)) {
                    $query->where("r.settle_state", $settle_state);
                }
                if (!empty($pur_manage_id)) {
                    $query->where("r.pur_manage_id", $pur_manage_id);
                }
                if (!empty($settle_sponsor_manage_id)) {
                    $query->where("r.settle_sponsor_manage_id", $settle_sponsor_manage_id);
                }
                if (!empty($settle_affirm_manage_id)) {
                    $query->where("r.settle_affirm_manage_id", $settle_affirm_manage_id);
                }
                if (!empty($return_manage_id)) {
                    $query->where("r.return_manage_id", $return_manage_id);
                }
                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('r.create_time', [$start_time, $end_time]);
                }

                //是否归还
                if (!empty($is_return)) {
                    $query->where("r.return_state", $is_return);
                }
                if (!empty($node)) {
                    $query->where("r.node", $node);
                }
            })->where(function ($query) use ($is_overdue, $is_return) {
                //是否逾期
                if (!empty($is_overdue)) {
                    //分为 归还成功 的逾期与未归还的逾期
                    if ($is_overdue == 1) {
                        if (empty($is_return)) {
                            $query->orWhere(function ($querys) {
                                $querys->where('r.return_state', 1)->where('r.expire_time', '>', date('Y-m-d H:i:s'));
                            });
                            $query->orWhere(function ($queryss) {
                                $queryss->orWhere('r.return_state', 2)->whereColumn('r.return_time', '<', 'r.expire_time');
                            });
                            $query->orWhere(function ($querysss) {
                                $querysss->orWhere('r.return_state', 3)->whereColumn('r.return_time', '<', 'r.expire_time');
                            });
                        } elseif ($is_return == 1) {
                            $query->where('r.expire_time', '>', date('Y-m-d H:i:s'));
                        } elseif ($is_return == 2) {
                            $query->whereColumn('r.return_time', '<', 'r.expire_time');
                        } elseif ($is_return == 3) {
                            $query->whereColumn('r.return_time', '<', 'r.expire_time');
                        }
                    } else {
                        if (empty($is_return)) {
                            $query->orWhere(function ($querys) {
                                $querys->where('r.return_state', 1)->where('r.expire_time', '<', date('Y-m-d H:i:s'));
                            });
                            $query->orWhere(function ($queryss) {
                                $queryss->orWhere('r.return_state', 2)->whereColumn('r.return_time', '>', 'r.expire_time');
                            });
                            $query->orWhere(function ($querysss) {
                                $querysss->orWhere('r.return_state', 3)->whereColumn('r.return_time', '>', 'r.expire_time');
                            });
                        } elseif ($is_return == 1) {
                            $query->where('r.expire_time', '<', date('Y-m-d H:i:s'));
                        } elseif ($is_return == 2) {
                            $query->whereColumn('r.return_time', '>', 'r.expire_time');
                        } elseif ($is_return == 3) {
                            $query->whereColumn('r.return_time', '>', 'r.expire_time');
                        }
                    }
                }
            })
            ->whereNotNull('order_id')
            ->where('r.type', 2)
            //  ->whereRaw(DB::raw('r.shop_id IS Null or r.shop_id = ""'))
            ->orderByDesc('r.id');

        if ($select_way == 1) {
            $res = $res->paginate($limit)
                ->toArray();
        } elseif ($select_way == 2) {
            $res = $res->groupBy('r.account_id')->pluck('r.id');
            return count($res);
        } elseif ($select_way == 3) {
            $res = $res->sum('r.price');
        } elseif ($select_way == 4) {
            $res = $res->count();
        }

        if ($select_way == 1) {
            $commonControllerObj = new CommonController();
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['pur_manage_name'] = !empty($val['pur_manage_id']) ? Manage::getManageNameByManageId($val['pur_manage_id']) : '';
                $res['data'][$key]['settle_sponsor_manage_name'] = !empty($val['settle_sponsor_manage_id']) ? Manage::getManageNameByManageId($val['settle_sponsor_manage_id']) : '';
                $res['data'][$key]['settle_affirm_manage_name'] = !empty($val['settle_affirm_manage_id']) ? Manage::getManageNameByManageId($val['settle_affirm_manage_id']) : '';
                $res['data'][$key]['return_manage_name'] = !empty($val['return_manage_id']) ? Manage::getManageNameByManageId($val['return_manage_id']) : '';

                $res['data'][$key]['overdue_day'] = $this->getOverdueDayMoney($val);

                $res['data'][$key][$commonControllerObj->list_index_key] = $commonControllerObj->addSerialNumberOne($key, $page, $limit);
                $res['data'][$key]['way'] = empty($val['order_id']) ? 2 : 1; //1 为 线上荐购 ， 2 为线下荐购
            }
            $res = $commonControllerObj->disPageData($res);
        }
        return $res;
    }



    /**
     * 获取新书采购清单详情
     * @param purchase_id  采购清单id
     */
    public function detail($purchase_id, $field = null)
    {

        if (empty($field)) {
            $field = [
                'r.id', 'r.order_id', 'r.barcode', 'l.account', 'b.book_name', 'b.author', 'b.isbn', 'b.press', 'b.pre_time', 'b.book_selector',
                'r.price', 'r.create_time', 'r.settle_state', 'r.settle_sponsor_time', 'r.settle_sponsor_manage_id', 'r.settle_affirm_manage_id', 'r.money_manage_id',
                'r.pur_manage_id', 'r.return_manage_id', 's.name as shop_name'
            ];
        }

        $res = $this->from($this->getTable() . ' as r')
            ->select($field)
            ->join('user_account_lib as l', 'l.id', '=', 'r.account_id')
            ->join('shop_book as b', 'b.id', '=', 'r.book_id')
            ->join('shop as s', 's.id', '=', 'b.shop_id')
            ->where('id', $purchase_id)
            ->first();

        if ($res) {
            //获取书籍信息
            $res['pur_manage_name'] = !empty($res['pur_manage_id']) ? Manage::getManageNameByManageId($res['pur_manage_id']) : '';
            $res['settle_sponsor_manage_name'] = !empty($res['settle_sponsor_manage_id']) ? Manage::getManageNameByManageId($res['settle_sponsor_manage_id']) : '';
            $res['settle_affirm_manage_name'] = !empty($res['settle_affirm_manage_id']) ? Manage::getManageNameByManageId($res['settle_affirm_manage_id']) : '';
            $res['return_manage_name'] = !empty($res['return_manage_id']) ? Manage::getManageNameByManageId($res['return_manage_id']) : '';
            $res['money_manage_name'] = !empty($res['money_manage_id']) ? Manage::getManageNameByManageId($res['money_manage_id']) : '';


            //计算逾期金额
            // list($res['overdue_day'], $res['overdue_money'], $res['drop_money'], $res['total_money'],) = $this->purchaseObj->getOverdueDayMoney($res);
            // //获取赔付比例
            // list($res['overdue_ratio'], $res['drop_ratio']) = $this->purchaseObj->penalSumParam($res['overdue_money'], $res['overdue_day'], $res['drop_money'], $res['price']);

            $bookHomeOrderModel = new BookHomeOrder();
            $res = $bookHomeOrderModel->checkBookHomePurchaseData($res);
        }
        return $res;
    }

    /**
     * 获取馆藏书采购清单详情
     * @param purchase_id  采购清单id
     */
    public function libDetail($purchase_id, $field = null)
    {

        if (empty($field)) {
            $field = [
                'r.id', 'r.order_id', 'r.barcode', 'l.account', 'b.book_name', 'b.author', 'b.isbn', 'b.press', 'b.pre_time', 'r.price', 'r.create_time',
                'r.settle_state', 'r.settle_sponsor_time', 'r.settle_sponsor_manage_id', 'r.settle_affirm_manage_id', 'r.pur_manage_id', 'r.return_manage_id', 'r.money_manage_id'
            ];
        }
        $res = $this->from($this->getTable() . ' as r')
            ->select($field)
            ->join('user_account_lib as l', 'l.id', '=', 'r.account_id')
            ->join('lib_book as b', 'b.id', '=', 'r.book_id')
            ->where('id', $purchase_id)
            ->first();

        if ($res) {
            //获取书籍信息
            $res['pur_manage_name'] = !empty($res['pur_manage_id']) ? Manage::getManageNameByManageId($res['pur_manage_id']) : '';
            $res['settle_sponsor_manage_name'] = !empty($res['settle_sponsor_manage_id']) ? Manage::getManageNameByManageId($res['settle_sponsor_manage_id']) : '';
            $res['settle_affirm_manage_name'] = !empty($res['settle_affirm_manage_id']) ? Manage::getManageNameByManageId($res['settle_affirm_manage_id']) : '';
            $res['return_manage_name'] = !empty($res['return_manage_id']) ? Manage::getManageNameByManageId($res['return_manage_id']) : '';
            $res['money_manage_name'] = !empty($res['money_manage_id']) ? Manage::getManageNameByManageId($res['money_manage_id']) : '';


            //计算逾期金额
            // list($res['overdue_day'], $res['overdue_money'], $res['drop_money'], $res['total_money'],) = $this->purchaseObj->getOverdueDayMoney($res);
            // //获取赔付比例
            // list($res['overdue_ratio'], $res['drop_ratio']) = $this->purchaseObj->penalSumParam($res['overdue_money'], $res['overdue_day'], $res['drop_money'], $res['price']);

            $bookHomeOrderModel = new BookHomeOrder();
            $res = $bookHomeOrderModel->checkBookHomePurchaseData($res);
        }
        return $res;
    }


    /**
     * 根据条形码，查询本地是否有借阅此书
     * @param $barcode  条形码
     */
    public function getBorrowInfoByBarcode($barcode, $field = null)
    {
        if (empty($field)) {
            $field = ['p.id', 'p.account_id', 'p.user_id', 'p.barcode', 'p.node', 'b.book_name', 'b.author', 'b.isbn', 'b.price', 'b.book_num', 'b.press', 'b.pre_time', 'b.intro', 'p.create_time', 'p.expire_time'];
        }
        $res = $this->from($this->getTable() . ' as p')
            ->select($field)
            ->leftjoin('shop_book as b', 'b.id', '=', 'p.book_id')
            ->where('barcode', $barcode)
            //->where('node', 2)
            ->whereIn('return_state', [1, 3])
            ->first();

        return $res;
    }
}
